import {defineStore} from "pinia";
import {ref} from 'vue';
import {whoAmI} from "@/api/user";
import {deleteStorage, getStorage, setStorage, USER_INFO, USER_TOKEN} from "@/utils/localStorage";

export default defineStore('user', () => {
    // 用户信息数据
    const userInfo = ref({});

    /**
     * 获取用户信息
     */
    function getInfo() {
        if (!getStorage(USER_TOKEN)) return
        whoAmI().then(({data}) => {
            userInfo.value = data;
            setStorage(USER_INFO, JSON.stringify(data))
        })
    }

    /**
     * 清空用户信息
     */
    function clearInfo() {
        deleteStorage(USER_INFO)
    }

    return {
        getInfo,
        clearInfo,
        userInfo
    }
})